﻿using eslib.nnp5;
using System;
using System.Collections.Generic;
using System.Text;

namespace eslib.DataRetrievalLib
{
    public class DataRetrieval
    {
        public DataRetrieval()
        {
            handlers = new List<DRHandler>();
            stream = new stream();
        }


        //重置
        public void reset()
        {
            stream.clear();
            setActiveHandler(0);
        }


        //添加处理器
        public void addHandler(DRHandler h)
        {
            handlers.Add(h);
        }


        //设置索引号为index的处理器为当前激活处理器，应用层添加处理器后必需设置0为活动处理器
        public void setActiveHandler(int index)
        {
            try
            {
                activeHandlerIndex = index;
                activeHandler = handlers[activeHandlerIndex];
            }
            catch
            {
                throw new NNP5Exception("匹配器异常：可能未添加处理器");
            }
        }


        //数据送入流
        public void inStream(byte ch)
        {
            activeHandler.inStream(ch);
        }



        //匹配事件观察者
        public void match_viewer()
        {
            if ((activeHandlerIndex + 1) == handlers.Count)
            {
                //全部匹配完成
                byte[] buf = this.stream.get();

                //通知应用层
                matchEvent?.Invoke(buf);

                //重置，为下一次作准备
                reset();        //包含了清空流
            }
            else
            {
                //下一次匹配
                setActiveHandler(activeHandlerIndex + 1);
            }
        }


        /// <summary>
        /// 成功匹配后引发
        /// </summary>
        public event match_handle matchEvent;




        private List<DRHandler> handlers;

        private DRHandler activeHandler;
        private int activeHandlerIndex = 0;


        internal stream stream { get; private set; }
    }



    /// <summary>
    /// 匹配成功处理委托
    /// </summary>
    /// <param name="buf"></param>
    public delegate void match_handle(byte[] buf);
}
